import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex)

const store = new Vuex.Store({
  state() {
    return {
      userInfo: uni.getStorageSync("userInfo") || null,
      cartList: uni.getStorageSync("cartList") || [],
      collectList: uni.getStorageSync("collectList") || [],
    }
  },
  mutations: {
    login(state, value) {
      state.userInfo = value

      uni.setStorage({
        key: "userInfo",
        data: state.userInfo,
      })
    },

    saveCart(state) {
      uni.setStorage({
        key: "cartList",
        data: state.cartList,
      })
    },

    addGoods(state, value) {
      const item = state.cartList.find((item) => {
        return item.goods_id == value.goods_id
      })
      if (item != undefined) {
        item.count++
      } else {
        state.cartList.push(value)
      }

      this.commit("saveCart")
    },

    countChange(state, value) {
      if (value.count == 0) {
        uni.showModal({
          title: "提示",
          content: "是否删除商品",
          cancelText: "取消",
          confirmText: "确定",
          success: (result) => {
            if (result.confirm) {
              const index = state.cartList.findIndex((item) => {
                return item.goods_id == value.goods.goods_id
              })
              state.cartList.splice(index, 1)
              this.commit("saveCart")
            }
          },
        })
      } else {
        value.goods.count = value.count
        this.commit("saveCart")
      }
    },

    checkedChange(state, value) {
      value.checked = !value.checked

      this.commit("saveCart")
    },

    selectAll(state, value) {
      state.cartList.forEach((item) => {
        item.checked = value
      })

      this.commit("saveCart")
    },

    collectGoods(state, value) {
      const index = state.collectList.findIndex((item) => {
        return item === value
      })

      if (index != -1) {
        state.collectList.splice(index, 1)
      } else {
        state.collectList.push(value)
      }

      uni.setStorage({
        key: "collectList",
        data: state.collectList,
      })
    },
  },

  getters: {
    isLogin(state) {
      return state.userInfo
    },
  },
})

export default store
